package com.hades.xq.miaoshao.controller;

import com.alibaba.druid.util.StringUtils;
import com.hades.xq.miaoshao.controller.viewobject.UserVO;
import com.hades.xq.miaoshao.error.BusinessException;
import com.hades.xq.miaoshao.error.EmBusinessError;
import com.hades.xq.miaoshao.response.CommonReturnType;
import com.hades.xq.miaoshao.service.UserService;
import com.hades.xq.miaoshao.service.model.UserModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * @CrossOrigin注解 1：解决跨域问题 from origin 'null' has been blocked by CORS policy:
 * No 'Access-Control-Allow-Origin' header is present on the requested resource.
 * <p>
 * 2：CrossOrigin的DEFAULT_ALLOWED_HEADERS：允许跨域传输所有的header参数，
 * 将用于使用tonek放入header域作为session共享的跨域请求，
 * 但是前端的ajax也必须加：xhrFields:{withCredentials: true}
 */
@Controller("/user")
@RequestMapping("/user")
@Slf4j
@CrossOrigin(origins = "*", allowCredentials = "true", allowedHeaders = "*")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private HttpServletRequest httpServletRequest;


    @RequestMapping(value = "/login", method = RequestMethod.POST, consumes = CONSUMES_TYPE_FORMED)
    @ResponseBody
    public CommonReturnType login(@RequestParam(name = "telphone") String telphone,
                                  @RequestParam(name = "password") String password) throws BusinessException,
            UnsupportedEncodingException, NoSuchAlgorithmException {

        if (StringUtils.isEmpty(telphone) || StringUtils.isEmpty(password)) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        UserModel userModel = userService.validateLogin(telphone, this.encodingMD5(password));
        this.httpServletRequest.getSession().setAttribute("IS_LOGIN", true);
        this.httpServletRequest.getSession().setAttribute("LOGIN_USER", userModel);
        return CommonReturnType.create(null);
    }

    @RequestMapping(value = "/regist", method = RequestMethod.POST, consumes = CONSUMES_TYPE_FORMED)
    @ResponseBody
    public CommonReturnType regist(@RequestParam(name = "telphone") String telphone,
                                   @RequestParam(name = "otpCode") String otpCode,
                                   @RequestParam(name = "name") String name,
                                   @RequestParam(name = "gender") Integer gender,
                                   @RequestParam(name = "age") Integer age,
                                   @RequestParam(name = "password") String password) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        log.info("regist().sessionID->" + httpServletRequest.getSession().getId());
        //验证手机号码和短信验证码是否一致
        String inSessionOtpCode = (String) this.httpServletRequest.getSession().getAttribute(telphone);
        log.info("inSessionOtpCode-->" + inSessionOtpCode);
        if (!StringUtils.equals(inSessionOtpCode, otpCode)) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "短信验证码不符合 ");
        }
        //用户注册流程
        UserModel userModel = new UserModel();
        userModel.setName(name);
        userModel.setAge(age);
        userModel.setGender(gender);
        userModel.setTelphone(telphone);
        userModel.setRegisterModel("byphone");
        userModel.setEncriptPassowrd(encodingMD5(password));
        userService.reginster(userModel);
        return CommonReturnType.create(null);
    }

    private String encodingMD5(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encode(md5.digest(password.getBytes("UTF-8")));
    }

    /**
     * 获取短信验证码
     *
     * @param telphone
     * @return
     * @throws BusinessException
     */
    @RequestMapping(value = "/getOtp", method = RequestMethod.POST, consumes = CONSUMES_TYPE_FORMED)
    @ResponseBody
    public CommonReturnType getOtp(@RequestParam(name = "telphone", required = false) String telphone) throws BusinessException {
        //按照一定规则，生成otp验证码
        if (StringUtils.isEmpty(telphone)) {
            throw new BusinessException(EmBusinessError.USER_UNINPUT_TELPHONE);
        }
        Random random = new Random();
        int randomInt = random.nextInt(99999);
        String randomString = String.valueOf((randomInt += 10000));
        log.info("randomString-->" + randomString);
        //将otp生成的验证码同手机号码关联，使用httpsession的方式绑定他的手机号码
        log.info("getOtp().sessionID->" + httpServletRequest.getSession().getId());
        httpServletRequest.getSession().setAttribute(telphone, randomString);
        log.info("手机号码：" + telphone + " ，短信验证码：" + randomString);
        return CommonReturnType.create(null);
    }


    @RequestMapping(value = "/getUser", method = RequestMethod.GET)
    @ResponseBody
    public CommonReturnType getUser(@RequestParam(name = "id") Integer id) throws BusinessException {
        UserModel userModel = userService.getUserById(id);
        if (userModel == null) {
            throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
        }
        UserVO vo = convertFromViewObject(userModel);
        return CommonReturnType.create(vo);
    }

    private UserVO convertFromViewObject(UserModel userModel) {
        if (userModel == null) {
            return null;
        }
        UserVO userVo = new UserVO();
        BeanUtils.copyProperties(userModel, userVo);
        return userVo;
    }
}